"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 防篡改
Case Name   : 创建普通用户验证超级用户对其他用户创建的表空间有create权限
Create At   : 2022/3/23
Owner       : @daiguatutu
Description :
    1.设置参数并重启数据库enableseparationofduty=on
    2.创建sysadmin用户和普通用户
    3.sysadmin用户连接,创建表空间
    4.普通用户连接,创建临时表，普通表和分区表
    5.普通用户连接,设置数据库默认的表空间
    6.sysadmin用户连接,将表空间的create权限赋予普通用户
    7.普通用户连接,创建临时表，普通表和分区表
    8.普通用户连接,设置数据库默认的表空间
    9.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.失败
    5.成功
    6.成功
    7.创建临时表成功，普通表和分区表创建失败
    8.成功
    9.清理环境成功
History     :
"""

import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import macro


class Security(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.common = Common()
        self.u_name = 'u_security_create_privilege_0002'
        self.u_name_01 = 'u_security_create_privilege_0002_01'
        self.ts_name = 'ts_security_create_privilege_0002'
        self.t_name = 't_security_create_privilege_0002'
        self.default_value1 = self.common.show_param('enableSeparationOfDuty')

    def test_security(self):
        text = '-----step1：设置参数并重启数据库enableSeparationOfDuty=on; ' \
               'expect:成功-----'
        self.log.info(text)
        mod_msg = self.pri_sh.execute_gsguc('set',
                                            self.constant.GSGUC_SUCCESS_MSG,
                                            'enableSeparationOfDuty=on')
        self.assertTrue(mod_msg, '执行失败:' + text)
        result = self.pri_sh.restart_db_cluster()
        self.assertTrue(result, '执行失败' + text)

        text = '-----step2：创建sysadmin用户和普通用户,表空间 expect:成功-----'
        self.log.info(text)
        create_cmd = f"drop tablespace if exists {self.ts_name};" \
            f"drop user if exists {self.u_name},{self.u_name_01} cascade; " \
            f"create user {self.u_name} sysadmin password " \
            f"'{macro.COMMON_PASSWD}';" \
            f"create user {self.u_name_01} password '{macro.COMMON_PASSWD}';"
        msg = self.pri_sh.execut_db_sql(create_cmd)
        self.log.info(msg)
        self.assertIn(self.constant.TABLESPCE_DROP_SUCCESS, msg,
                      '执行失败:' + text)
        self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, msg,
                      '执行失败:' + text)
        self.assertEqual(2, msg.count(self.constant.CREATE_ROLE_SUCCESS_MSG),
                         '执行失败:' + text)

        text = '-----step3：sysadmin用户连接,创建表空间; expect:成功-----'
        self.log.info(text)
        sql_cmd = f"drop tablespace if exists {self.ts_name};" \
            f"create tablespace {self.ts_name} relative " \
            f"location '{self.ts_name}';"
        connect_sys = f'-U {self.u_name} -W {macro.COMMON_PASSWD}'
        msg = self.pri_sh.execut_db_sql(sql_cmd, sql_type=connect_sys)
        self.log.info(msg)
        self.assertIn(self.constant.TABLESPCE_DROP_SUCCESS, msg,
                      '执行失败:' + text)
        self.assertIn(self.constant.TABLESPCE_CREATE_SUCCESS, msg,
                      '执行失败:' + text)

        text = '-----step4：普通用户连接,创建临时表，普通表和分区表; expect:失败-----'
        self.log.info(text)
        create_cmd = f"drop table if exists {self.t_name}; " \
            f"create local temp table {self.t_name}(" \
            f"id int primary key,name varchar(100)) " \
            f"tablespace {self.ts_name};" \
            f"drop table if exists public.{self.t_name}; " \
            f"create table public.{self.t_name}(id int primary key," \
            f"name varchar(100)) tablespace {self.ts_name};" \
            f"create table public.{self.t_name}(id int,name varchar(100)) " \
            f"partition by range(id) ( " \
            f"partition p1 values less than(10) tablespace {self.ts_name}, " \
            f"partition p2 values less than(20) tablespace {self.ts_name}, " \
            f"partition p3 values less than(30) tablespace {self.ts_name}, " \
            f"partition pmax values less than(maxvalue) " \
            f"tablespace {self.ts_name} );"
        connect_nor = f'-U {self.u_name_01} -W {macro.COMMON_PASSWD}'
        msg = self.pri_sh.execut_db_sql(create_cmd, sql_type=connect_nor)
        self.log.info(msg)
        self.assertEqual(2, msg.count(self.constant.DROP_TABLE_SUCCESS),
                         '执行失败:' + text)
        self.assertEqual(3, msg.count('ERROR:  permission denied'),
                         '执行失败:' + text)

        text = '-----step5：普通用户连接,设置数据库默认的表空间; expect:成功-----'
        self.log.info(text)
        set_cmd = f"set default_tablespace = {self.ts_name};"
        msg = self.pri_sh.execut_db_sql(set_cmd, sql_type=connect_nor)
        self.log.info(msg)
        self.assertIn(self.constant.SET_SUCCESS_MSG, msg, '执行失败:' + text)

        text = '-----step6：sysadmin用户连接,将表空间的create权限赋予普通用户; expect:成功-----'
        self.log.info(text)
        sql_cmd = f"grant create on tablespace {self.ts_name} " \
            f"to {self.u_name_01};"
        connect_sys = f'-U {self.u_name} -W {macro.COMMON_PASSWD}'
        msg = self.pri_sh.execut_db_sql(sql_cmd, sql_type=connect_sys)
        self.log.info(msg)
        self.assertIn(self.constant.GRANT_SUCCESS_MSG, msg, '执行失败:' + text)

        text = '-----step7：普通用户连接,创建临时表，普通表和分区表; ' \
               'expect:创建临时表成功，普通表和分区表创建失败-----'
        self.log.info(text)
        msg = self.pri_sh.execut_db_sql(create_cmd, sql_type=connect_nor)
        self.log.info(msg)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, msg.splitlines()[2],
                      '执行失败:' + text)
        self.assertEqual(2, msg.count(self.constant.DROP_TABLE_SUCCESS),
                         '执行失败:' + text)
        self.assertEqual(2, msg.count('ERROR:  permission denied'),
                         '执行失败:' + text)

        text = '-----step8：普通用户连接,设置数据库默认的表空间; expect:成功-----'
        self.log.info(text)
        msg = self.pri_sh.execut_db_sql(set_cmd, sql_type=connect_nor)
        self.log.info(msg)
        self.assertIn(self.constant.SET_SUCCESS_MSG, msg, '执行失败:' + text)

    def tearDown(self):
        self.log.info('-----step9：清理环境-----')
        text1 = '-----删除用户 expect:成功-----'
        self.log.info(text1)
        drop_cmd = f"drop tablespace if exists {self.ts_name};" \
            f"drop user if exists {self.u_name},{self.u_name_01} cascade;"
        drop_msg = self.pri_sh.execut_db_sql(drop_cmd)
        self.log.info(drop_msg)

        text2 = '-----修改参数enableSeparationOfDuty为初始值 expect:成功-----'
        self.log.info(text2)
        mod_msg1 = self.pri_sh.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f'enableSeparationOfDuty='
                                             f'{self.default_value1}')
        restart_res = self.pri_sh.restart_db_cluster()

        self.log.info('-----断言tearDown执行成功-----')
        self.assertIn(self.constant.TABLESPCE_DROP_SUCCESS, drop_msg,
                      '执行失败:' + text1)
        self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, drop_msg,
                      '执行失败:' + text1)
        self.assertTrue(mod_msg1, '执行失败:' + text2)
        self.assertTrue(restart_res, '执行失败:' + text2)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
